package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 */
public class CookieUtil {
//    添加cookie
    public static void addCookie(String name, String value, int time, HttpServletResponse response){
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(time);//设置存活市场
        cookie.setPath("/"); //共享路径
        response.addCookie(cookie);
    }

    public static String getToken(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        String token = null;
        if(cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //找到对应我们存进去的name为token的cookie
                if ("token".equals(cookie.getName())) {
                    //通过value值再拼接前缀作为key去redis找到对应的user对象
                    token = cookie.getValue();
                    cookie.setPath("/");
                    cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return token;
    }
}
